package com.hhck.service.impl;

import com.hhck.entity.InStore;
import com.hhck.entity.Page;
import com.hhck.entity.Purchase;
import com.hhck.entity.Result;
import com.hhck.mapper.InStoreMapper;
import com.hhck.mapper.PurchaseMapper;
import com.hhck.service.PurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PurchaseServiceImpl implements PurchaseService {

    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private InStoreMapper inStoreMapper;

    /**
     * 添加采购单（商品采购）
     */
    @Override
    public Result savePurchase(Purchase purchase) {

        int num = purchaseMapper.insertPurchase(purchase);
        if (num == 1) {
            return Result.ok("添加成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "添加失败！");
    }

    /**
     * 分页查询采购单列表（条件查询）
     */
    @Override
    public Page queryPurchaseListByPage(Page page, Purchase purchase) {

        // 分页查询采购单（条件查询）
        List<Purchase> purchaseList = purchaseMapper.selectPurchaseListByPage(page, purchase);

        // 查询采购单总行数（条件查询）
        int count = purchaseMapper.selectPurchaseCount(purchase);

        // 设置总行数
        page.setTotalNum(count);
        // 设置总页数
        page.setPageCount(page.getPageCount());

        // 封装采购单信息
        page.setResultList(purchaseList);

        return page;
    }

    /**
     * 删除采购单
     */
    @Override
    public Result removePurchaseByBuyId(Integer buyId) {

        int num = purchaseMapper.deletePurchaseByBuyId(buyId);
        if (num == 1) {
            return Result.ok("删除成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "删除失败！");
    }

    /**
     * 修改采购单
     */
    @Override
    public Result modifyPurchaseByBuyId(Purchase purchase) {

        int num = purchaseMapper.updatePurchaseByBuyId(purchase);
        if (num == 1) {
            return Result.ok("修改成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "修改失败！");
    }

    /**
     * 生成入库单
     */
    // 开启事务
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result saveInStore(Purchase purchase, Integer createBy) {

        // 修改采购单为已入库状态
        int num = purchaseMapper.updatePurchaseIsInByBuyId(purchase);

        // 创建入库单对象
        InStore inStore = new InStore();
        inStore.setStoreId(purchase.getStoreId());
        inStore.setProductId(purchase.getProductId());
        inStore.setInNum(purchase.getFactBuyNum());
        inStore.setCreateBy(createBy);

        // 生成入库单
        num += inStoreMapper.insertInStore(inStore);

        if (num == 2) {
            return Result.ok("添加成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "添加失败！");
    }

}

